// @ts-nocheck
import React, { useState } from 'react';
import {Editor} from 'amis-editor';
import '@fortawesome/fontawesome-free/css/all.css';
import '@fortawesome/fontawesome-free/css/v4-shims.css';
import 'amis-editor-core/lib/style.css';
import 'amis/lib/helper.css';
import 'amis/lib/themes/cxd.css';
import 'amis/sdk/iconfont.css';
import {message} from "antd";

import { alert, AlertComponent, confirm, ToastComponent } from 'amis-ui';
// React 版本 英文翻译
import 'amis-ui/lib/locale/en-US';
import copy from 'copy-to-clipboard';

import request from '@/utils/request';

// 布局组件
//import LayoutList from '@/components/Amis/plugin/layout/index'
//验证码组件
import AJCaptchaRendererPlugin from '@/components/Amis/plugin/AJCaptchaRendererPlugin'
import IFramePlusPlugin from "@/components/Amis/plugin/IFramePlusPlugin";
import {saveSchame} from "@/services/menu.ts";
import {useParams} from "react-router-dom";
import {DesktopOutlined, MobileOutlined} from "@ant-design/icons";
import {Button,Space} from "antd";
import {useRequest} from "ahooks";

interface EditorProps {
  schema?: any;
  id?: string;
}

const AMISEditor: React.FC<EditorProps> = (props) => {


  const [preview, setPreview] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [schemaJson, setSchemaJson] = useState({});
  const {loading,runAsync} = useRequest(saveSchame,{
    manual:true,
    onSuccess: (result, params) => {
      console.log('---saveSchame--',result,params)
      result.data.code ===200 ?message.success(result.data.msg):message.error(result.data.msg);
    }
  })
  // let amisScoped;
  const theme = 'cxd';
  // 当前语言
  const curLanguage = "zh-CN";

  const schema = props.schema;
  const {id} = useParams();

  function exit() {
    window.close();
  }

  function save() {
    console.log('save',id,schemaJson)
    // @ts-ignore
    runAsync(id,schemaJson);
  }

  function onChange(value: any) {
    setSchemaJson(value);
  }

  return (
    <div className="Editor-Demo">
      <div className="Editor-header">
        <div className="Editor-title">可视化编辑器</div>
        <div className="Editor-view-mode-group-container">
          <div className="Editor-view-mode-group">
            <div
              className={`Editor-view-mode-btn editor-header-icon ${!isMobile ? 'is-active' : ''}`}
              onClick={() => {
                setIsMobile(false);
              }}
            >
              {/* PC模式 */}
              <DesktopOutlined />
            </div>
            <div
              className={`Editor-view-mode-btn editor-header-icon ${isMobile ? 'is-active' : ''}`}
              onClick={() => {
                setIsMobile(true);
              }}
            >
              {/* 移动模式 */}
              <MobileOutlined />
            </div>
          </div>
        </div>

        <div className="Editor-header-actions">
          <Space>
          {/* 语言选择 */}
          <Button type={preview?'primary':'default'}  onClick={() => {
            setPreview(!preview);
          }}>{preview ? '编辑' : '预览'}</Button>
          {/* 保存 */}
          {!preview && (
            <Button type="primary" loading={loading} onClick={save}>保存</Button>
          )}
          {/* 退出 */}
          {!preview && (
              <Button type="primary" danger onClick={exit}>退出</Button>
          )}
          </Space>
        </div>
      </div>

      <div className="Editor-inner">
        <ToastComponent theme={theme} key="toast" position={'top-center'} locale={curLanguage} />
        <AlertComponent theme={theme} key="alert" locale={curLanguage} />

        <Editor
          value={schema}
          theme={theme}
          isMobile={isMobile}
          preview={preview}
          onChange={onChange}
          // 扩展插件
          plugins={[AJCaptchaRendererPlugin,IFramePlusPlugin]}
          onSave={save}
          onPreview={() => {
            setPreview(true);
          }}
          amisEnv={{
            fetcher: ({
              url, // 接口地址
              method, // 请求方法 get、post、put、delete
              data, // 请求数据
              responseType,
              config, // 其他配置
              headers, // 请求头
            }: any) => {
              config = config || {};
              config.withCredentials = true;
              responseType && (config.responseType = responseType);

              if (config.cancelExecutor) {
                config.cancelToken = new (request as any).CancelToken(config.cancelExecutor);
              }

              config.headers = headers || {};

              if (method !== 'post' && method !== 'put' && method !== 'patch') {
                if (data) {
                  config.params = data;
                }

                return (request as any)[method](url, config);
              } else if (data && data instanceof FormData) {
                config.headers = config.headers || {};
                config.headers['Content-Type'] = 'multipart/form-data';
              } else if (
                data &&
                typeof data !== 'string' &&
                !(data instanceof Blob) &&
                !(data instanceof ArrayBuffer)
              ) {
                data = JSON.stringify(data);
                config.headers = config.headers || {};
                config.headers['Content-Type'] = 'application/json';
              }

              return (request as any)[method](url, data, config);
            },
            copy: (content) => {
              copy(content);
              message.success('内容已复制到粘贴板');
            },
            // @ts-nocheck
            notify: (
                type: 'success' | 'error' | 'info', msg: string
            ) => {
              console.log('notify',type,msg)
              message[type](msg,5)
            },
            alert: alert,
            confirm: confirm,
          }}
        />
      </div>
    </div>
  );
};

export default AMISEditor;
